//
//  WKEditViewController.m
//  Walk
//
//  Created by cesh on 16/9/5.
//  Copyright © 2016年 cesh. All rights reserved.
//

#import "WKEditViewController.h"
#import "UITextView+Placeholder.h"
#import "WKBubbleViewController.h"
#import "WKSchoolViewController.h"
#import "WKMajorViewController.h"
#import "WKPicClipViewController.h"
#import "JPUSHService.h"
#import "WKPhoneAuthViewController.h"
#import <EMSDK.h>
#import <SVProgressHUD.h>
#import <IQKeyboardManager.h>
@interface WKEditViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate, SchoolDelegate, MajorDelegate, PicClipDelegate, PhoneAuthDelegate>

//datePicker相关控件
@property (strong, nonatomic) UIDatePicker *datePicker;
@property (strong, nonatomic) UIView *bgView;
@property (strong, nonatomic) UIButton *confirmBtn;
@property (strong, nonatomic) UIButton *cancelBtn;


@property (weak, nonatomic) IBOutlet UITextView *introductionTextView;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;

@property (weak, nonatomic) IBOutlet UIView *view1;
@property (weak, nonatomic) IBOutlet UIImageView *imageV1;

@property (weak, nonatomic) IBOutlet UIView *view2;
@property (weak, nonatomic) IBOutlet UIImageView *imageV2;

@property (weak, nonatomic) IBOutlet UIView *view3;
@property (weak, nonatomic) IBOutlet UIImageView *imageV3;

@property (weak, nonatomic) IBOutlet UIView *view4;
@property (weak, nonatomic) IBOutlet UIImageView *imageV4;

@property (weak, nonatomic) IBOutlet UIView *view5;
@property (weak, nonatomic) IBOutlet UIImageView *imageV5;

@property (weak, nonatomic) IBOutlet UIView *view6;
@property (weak, nonatomic) IBOutlet UIImageView *imageV6;


@property (strong, nonatomic) UIImageView *currentImgV;


@property (weak, nonatomic) IBOutlet UIView *genderView;
@property (weak, nonatomic) IBOutlet UILabel *genderLabel;

@property (weak, nonatomic) IBOutlet UIView *birthdayView;
@property (weak, nonatomic) IBOutlet UILabel *birthdayLabel;

@property (weak, nonatomic) IBOutlet UIView *phoneView;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet UIView *bottomView;

@property (weak, nonatomic) IBOutlet UIButton *topCancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *topSaveBtn;

@property (weak, nonatomic) IBOutlet UIView *schoolView;
@property (weak, nonatomic) IBOutlet UILabel *schoolLbl;

@property (weak, nonatomic) IBOutlet UIView *majorView;
@property (weak, nonatomic) IBOutlet UILabel *majorLbl;

@property (weak, nonatomic) IBOutlet UILabel *phoneLbl;
@end

@implementation WKEditViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    self.bottomConstraint.constant = self.bottomView.bottom + 10;
    
    self.phoneView.userInteractionEnabled = [self.phoneLbl.text length] > 0 ? NO : YES;
    if (self.phoneView.isUserInteractionEnabled) {
        UITapGestureRecognizer *tapOnPhoneView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bindPhone)];
        [self.phoneView addGestureRecognizer:tapOnPhoneView];
    }
}

- (void)bindPhone {
    WKPhoneAuthViewController *phoneAuthVC = [[WKPhoneAuthViewController alloc]init];
    phoneAuthVC.delegate = self;
    [self presentViewController:phoneAuthVC animated:YES completion:nil];
}
//绑定手机的回调

- (void)getPhoneNumber:(NSString *)phone {
    self.phoneLbl.text = phone;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    //数据持久化
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:userInfoPath];
    self.nameTextField.text = dict[@"nickname"];
    self.genderLabel.text = [dict[@"sex"] isEqual:@"1"] ? @"男" : @"女";
    self.birthdayLabel.text = dict[@"birthday"];
    self.phoneLbl.text = dict[@"phoneNumber"];
    
    if (dict[@"describe"]) {
        self.introductionTextView.text = dict[@"describe"];
    }
    
    if (dict[@"school"]) {
        self.schoolLbl.text = dict[@"school"];
    }if (dict[@"major"]) {
        self.majorLbl.text = dict[@"major"];
    }
    
    //设置图片
    NSArray *userImgs = [NSArray arrayWithContentsOfFile:userImagesPath];
    for (NSInteger i = 0; i < userImgs.count; i++) {
        UIImage *img = [UIImage imageWithData:userImgs[i]];
        if (i == 0) {
            self.imageV1.image = img;
            for (UIView *view in self.imageV1.superview.subviews) {
                if ([view isKindOfClass:[UIButton class]]) {
                    UIButton *button = (UIButton *)view;
                    button.tag = 1;
                    [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
                }
            }
        }
        if (i == 1) {
            self.imageV2.image = img;
            for (UIView *view in self.imageV2.superview.subviews) {
                if ([view isKindOfClass:[UIButton class]]) {
                    UIButton *button = (UIButton *)view;
                    button.tag = 1;
                    [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
                }
            }
        }
        if (i == 2) {
            self.imageV3.image = img;
            for (UIView *view in self.imageV3.superview.subviews) {
                if ([view isKindOfClass:[UIButton class]]) {
                    UIButton *button = (UIButton *)view;
                    button.tag = 1;
                    [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
                }
            }
        }
        if (i == 3) {
            self.imageV4.image = img;
            for (UIView *view in self.imageV4.superview.subviews) {
                if ([view isKindOfClass:[UIButton class]]) {
                    UIButton *button = (UIButton *)view;
                    button.tag = 1;
                    [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
                }
            }
        }
        if (i == 4) {
            self.imageV5.image = img;
            for (UIView *view in self.imageV5.superview.subviews) {
                if ([view isKindOfClass:[UIButton class]]) {
                    UIButton *button = (UIButton *)view;
                    button.tag = 1;
                    [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
                }
            }
        }
        if (i == 5) {
            self.imageV6.image = img;
            for (UIView *view in self.imageV6.superview.subviews) {
                if ([view isKindOfClass:[UIButton class]]) {
                    UIButton *button = (UIButton *)view;
                    button.tag = 1;
                    [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
                }
            }
        }
    }
    
    
    //如果是第一次进入app
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"didLogin"]) {
        self.topCancelBtn.hidden = YES;
        [self.topSaveBtn setTitle:@"提交" forState:UIControlStateNormal];
    }
    self.datePicker.date = [NSDate date];
    //设置6个图片
    [self setupPics];
    //设置简介的placeholder
    self.introductionTextView.placeholder = @"我就是我，是不一样的烟火，只为自己带盐。\n我是蛙客，拒绝独行！";
    self.introductionTextView.placeholderLabel.font = [UIFont systemFontOfSize:12.0];
    self.introductionTextView.placeholderColor = [UIColor colorWithRed:0xd8 / 255.0 green:0xd8 / 255.0 blue:0xd8 / 255.0 alpha:1.0];
    //点击背景退出键盘
    UITapGestureRecognizer *tapOnBg = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(resignKeyboard)];
    [self.view addGestureRecognizer:tapOnBg];
    //点击性别
    UITapGestureRecognizer *tapOnGenderV = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(gender)];
    [self.genderView addGestureRecognizer:tapOnGenderV];
    //点击生日
    UITapGestureRecognizer *tapOnBirthdayV = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(birthday)];
    [self.birthdayView addGestureRecognizer:tapOnBirthdayV];
    //点击学校
    UITapGestureRecognizer *tapOnSchool = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(school)];
    [self.schoolView addGestureRecognizer:tapOnSchool];
    //点击专业
    UITapGestureRecognizer *tapOnmajor = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(major)];
    [self.majorView addGestureRecognizer:tapOnmajor];
}

- (void)setupPics {
    self.view1.layer.cornerRadius = 4.0;
    self.view1.layer.masksToBounds = YES;
    
    self.view2.layer.cornerRadius = 4.0;
    self.view2.layer.masksToBounds = YES;
    
    self.view3.layer.cornerRadius = 4.0;
    self.view3.layer.masksToBounds = YES;
    
    self.view4.layer.cornerRadius = 4.0;
    self.view4.layer.masksToBounds = YES;
    
    self.view5.layer.cornerRadius = 4.0;
    self.view5.layer.masksToBounds = YES;
    
    self.view6.layer.cornerRadius = 4.0;
    self.view6.layer.masksToBounds = YES;
}

#pragma mark - 添加图片相关

- (IBAction)addPicBtn:(UIButton *)button {
    //如果当前的按钮是＋号,即tag为0，则添加图片
    if (button.tag == 0) {
        //记录要添加进入的imgV
        for (UIView *view in button.superview.subviews) {
            if ([view isKindOfClass:[UIImageView class]]) {
                self.currentImgV = (UIImageView *)view;
            }
        }
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        UIAlertAction *albumPic = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //图片选择控制器
            UIImagePickerController *imagePickerC = [[UIImagePickerController alloc]init];
            //设置进入本地的哪个相册
            imagePickerC.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            //设置代理实现图片的选中
            imagePickerC.delegate = self;
            [self presentViewController:imagePickerC animated:YES completion:nil];
        }];
        UIAlertAction *camera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //图片选择控制器
            UIImagePickerController *imagePickerC = [[UIImagePickerController alloc]init];
            //设置进入照相机
            imagePickerC.sourceType = UIImagePickerControllerSourceTypeCamera;
            //设置代理实现图片的选中
            imagePickerC.delegate = self;
            [self presentViewController:imagePickerC animated:YES completion:nil];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alert addAction:albumPic];
        [alert addAction:camera];
        [alert addAction:cancel];
        [self presentViewController:alert animated:YES completion:nil];
    }
    //当前按钮是X号，tag为1，删除图片
    else {
        for (UIView *view in button.superview.subviews) {
            if ([view isKindOfClass:[UIImageView class]]) {
                UIImageView *imgV = (UIImageView *)view;
                imgV.image = nil;
            }
        }
        button.tag = 0;
        [button setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    }
}
//UIImagePickerControllerDelegate方法，本地相册和照相机照下来的照片选中后做如下操作
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //获取选中的图片
    UIImage *selectedImage =  info[UIImagePickerControllerOriginalImage];
    //图片剪裁界面
    WKPicClipViewController *picClipVC = [[WKPicClipViewController alloc]init];
    picClipVC.delegate = self;
    picClipVC.img = selectedImage;
    
    //更改按钮的背景图片
    for (UIView *view in self.currentImgV.superview.subviews) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *button = (UIButton *)view;
            //将按钮的tag设为1，便于识别
            button.tag = 1;
            [button setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
        }
    }
    //退出图片选择器
    [self dismissViewControllerAnimated:NO completion:nil];
    [self presentViewController:picClipVC animated:NO completion:nil];
}

- (void)picClipViewController:(WKPicClipViewController *)picClipViewController clippedImage:(UIImage *)clippedImage {
    self.currentImgV.image = clippedImage;
}



- (void)gender {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *male = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.genderLabel.text = @"男";
    }];
    UIAlertAction *female = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.genderLabel.text = @"女";
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:male];
    [alert addAction:female];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
#pragma mark - 日期选择器
- (UIDatePicker *)datePicker {
    if (_datePicker == nil) {
        //调用自定义的datePicker
        UIDatePicker *datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, screenH / 2 , screenW, screenH / 2)];
        datePicker.datePickerMode = UIDatePickerModeDate;
        datePicker.locale = [NSLocale currentLocale];
        datePicker.backgroundColor = [UIColor whiteColor];
        NSTimeInterval age18 = 18 * 365 * 24 * 3600.0 + 5 * 24 * 3600.0;
        NSTimeInterval age50 = 50 * 365 * 24 * 3600.0;
        NSDate *minDate = [[NSDate alloc]initWithTimeIntervalSinceNow:-age50];
        NSDate *maxDate = [[NSDate alloc]initWithTimeIntervalSinceNow:-age18];
        
        datePicker.minimumDate = minDate;
        datePicker.maximumDate = maxDate;
        
        _datePicker = datePicker;
    }
    return _datePicker;
}

- (void)birthday {
    //添加背景蒙板
    UIView *bgView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    bgView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view addSubview:bgView];
    //给系统datePicker添加取消和确定按钮
    UIButton *confirm = [[UIButton alloc]initWithFrame:CGRectMake(screenW / 2, screenH / 2 , screenW / 2, 44)];
    UIButton *cancel = [[UIButton alloc]initWithFrame:CGRectMake(0, screenH / 2 , screenW / 2, 44)];
    [confirm setTitle:@"确认" forState:UIControlStateNormal];
    [confirm setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [confirm setBackgroundColor:[UIColor whiteColor]];
    [confirm addTarget:self action:@selector(confirm) forControlEvents:UIControlEventTouchUpInside];
    
    [cancel setTitle:@"取消" forState:UIControlStateNormal];
    [cancel setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [cancel setBackgroundColor:[UIColor whiteColor]];
    [cancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    
    [self resignKeyboard];
    //将datePicker加在keyWindow上
    [[UIApplication sharedApplication].keyWindow addSubview:self.datePicker];
    [[UIApplication sharedApplication].keyWindow addSubview:confirm];
    [[UIApplication sharedApplication].keyWindow addSubview:cancel];
    
    self.confirmBtn = confirm;
    self.cancelBtn = cancel;
    self.bgView = bgView;
}

- (void)confirm {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy/MM/dd"];
    NSString *strDate = [dateFormatter stringFromDate:self.datePicker.date];
    
    self.birthdayLabel.text = strDate;
    [self cancel];
    
}

- (void)cancel {
    //删去蒙板
    [self.bgView removeFromSuperview];
    //移除datePicker及两个按钮
    [self.datePicker removeFromSuperview];
    [self.confirmBtn removeFromSuperview];
    [self.cancelBtn removeFromSuperview];
}


- (void)resignKeyboard {
    [self.introductionTextView resignFirstResponder];
    [self.nameTextField resignFirstResponder];
}
//学校相关方法
- (void)school {
    WKSchoolViewController *schoolVC =  [[WKSchoolViewController alloc]init];
    schoolVC.delegate = self;
    [self presentViewController:schoolVC animated:YES completion:nil];
}

- (void)reloadSchool:(NSString *)school schoolID:(NSString *)schoolID {
    [[NSUserDefaults standardUserDefaults]setObject:schoolID forKey:@"schoolID"];
    self.schoolLbl.text = school;
}
//专业相关方法
- (void)major {
    WKMajorViewController *majorVC =  [[WKMajorViewController alloc]init];
    majorVC.delegate = self;
    [self presentViewController:majorVC animated:YES completion:nil];
}

- (void)reloadMajor:(NSString *)major majorID:(NSString *)majorID {
    [[NSUserDefaults standardUserDefaults]setObject:majorID forKey:@"majorID"];
    self.majorLbl.text = major;
}
- (IBAction)cancel:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)save:(id)sender {
    
    
    if ([self.nameTextField.text length] == 0 || [self.birthdayLabel.text length] == 0 ||[self.phoneLbl.text length] == 0 || self.imageV1.image == nil || [self.schoolLbl.text isEqualToString:@"没有填写"]) {
        [SVProgressHUD showInfoWithStatus:@"资料不完全"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    NSString *birthday = [self.birthdayLabel.text substringWithRange:NSMakeRange(0, 4)];
    
    //拦截年龄<18的情况
    if ([birthday integerValue] > 1998  ) {
        [SVProgressHUD showInfoWithStatus:@"年龄要大于18岁哦"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
        return;
    }
    
    //将图片二进制保存到本地／将图片存到数组中，便于上传
    NSMutableArray *imgsLocal = [NSMutableArray array];
    NSMutableArray *imgs = [NSMutableArray array];
    
    if (self.imageV1.image) {
        NSData *img1 = UIImageJPEGRepresentation(self.imageV1.image, 1);
        [imgs addObject:self.imageV1.image];
        [imgsLocal addObject:img1];
    }
    if (self.imageV2.image) {
        NSData *img2 = UIImageJPEGRepresentation(self.imageV2.image, 1);
        [imgs addObject:self.imageV2.image];
        [imgsLocal addObject:img2];
    }
    if (self.imageV3.image) {
        NSData *img3 = UIImageJPEGRepresentation(self.imageV3.image, 1);
        [imgs addObject:self.imageV3.image];
        [imgsLocal addObject:img3];
    }
    if (self.imageV4.image) {
        NSData *img4 = UIImageJPEGRepresentation(self.imageV4.image, 1);
        [imgs addObject:self.imageV4.image];
        [imgsLocal addObject:img4];
    }
    if (self.imageV5.image) {
        NSData *img5 = UIImageJPEGRepresentation(self.imageV5.image, 1);
        [imgs addObject:self.imageV5.image];
        [imgsLocal addObject:img5];
    }
    if (self.imageV6.image) {
        NSData *img6 = UIImageJPEGRepresentation(self.imageV6.image, 1);
        [imgs addObject:self.imageV6.image];
        [imgsLocal addObject:img6];
    }
    [imgsLocal writeToFile:userImagesPath atomically:YES];
    
    //发送图片
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithContentsOfFile:userInfoPath];
    NSMutableArray *imgsIDs = [NSMutableArray array];
    for (NSInteger i = 0; i < imgs.count; i++) {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        //接收类型不一致请替换一致text/html或别的
        manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",
                                                             @"text/html",
                                                             @"image/jpeg",
                                                             @"image/png",
                                                             @"application/octet-stream",
                                                             @"text/json",
                                                             @"text/plain",
                                                             nil];
        NSDictionary * dict = @{
                                @"token" : [userInfo valueForKey:@"token"],
                                @"imgType" : i == 0 ? @"1" : @"2"
                                };
        [manager POST:[NSString stringWithFormat:@"%@User/uploadUserImg", URL] parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            
            NSData *imageData = UIImageJPEGRepresentation(imgs[i], 1);
            
            if (imageData.length > 5000000) {
                imageData = UIImageJPEGRepresentation(imgs[i], 0.1);
            }
            else if (imageData.length > 3000000) {
                imageData = UIImageJPEGRepresentation(imgs[i], 0.3);
            }
            else if (imageData.length > 1000000) {
                imageData = UIImageJPEGRepresentation(imgs[i], 0.5);
            }
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            formatter.dateFormat = @"yyyyMMddHHmmss";
            NSString *str = [formatter stringFromDate:[NSDate date]];
            NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
            
            //上传的参数(上传图片，以文件流的格式)
            [formData appendPartWithFileData:imageData
                                        name:@"file"
                                    fileName:fileName
                                    mimeType:@"image/jpeg"];
            
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            //打印下上传进度
            NSLog(@"%@", uploadProgress);
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            //上传成功
            NSLog(@"上传图片 %@", responseObject);
            NSDictionary *dict = @{
                                   @"imgType" : i == 0 ? @"1" : @"2", // 该图片是否是头像
                                   @"id" : responseObject[@"data"][0][@"id"] //图片的id
                                   };
            [imgsIDs addObject:dict];
            NSLog(@"%@", imgsIDs);
            //当所有的图片都上传完成并收到了ID后再发送保存所有数据的请求
            if (imgsIDs.count == imgs.count) {
                //保存所有
                [self saveAll:imgsIDs];
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            //上传失败
            NSLog(@"上传图片 失败 %@", error);
        }];
    }
    
    
    //如果是第一次进入app，设置完个人资料之后，点保存进入气泡界面
    if (![[NSUserDefaults standardUserDefaults] boolForKey:@"didLogin"]) {
        //设置选性别不限
        [[NSUserDefaults standardUserDefaults]setInteger:1  forKey:@"selectedGender"];
        //获取环信的用户名和密码
        NSString *hx_user = userInfo[@"hx_user"];
        NSString *hx_pwd = userInfo[@"hx_pwd"];
        //环信登录操作
        EMError *error = [[EMClient sharedClient] loginWithUsername:hx_user password:hx_pwd];
        if (!error) {
            NSLog(@"环信登录成功");
            [[EMClient sharedClient] setApnsNickname:self.nameTextField.text];
        }
        else {
            NSLog(@"环信登录失败 %@", error);
        }
        
        WKBubbleViewController *bubbleVC = [[WKBubbleViewController alloc]init];
        CATransition *anim = [CATransition animation];
        anim.type = @"rippleEffect";
        anim.duration = 1.0;
        [[UIApplication sharedApplication].keyWindow.layer addAnimation:anim forKey:nil];
        
        [UIApplication sharedApplication].keyWindow.rootViewController = bubbleVC;
        //设置完个人资料之后，设置为已登录，以便下一次直接进入气泡界面
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"didLogin"];
    }
    else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)saveAll:(NSArray *)imgIDs {
    //保存设置和图片
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithContentsOfFile:userInfoPath];
    //昵称
    [userInfo setValue:self.nameTextField.text forKey:@"nickname"];
    //1 男 2 女
    NSString *sex = [self.genderLabel.text isEqualToString:@"男"] ? @"1" : @"2";
    [userInfo setValue:sex forKey:@"sex"];
    
    //获取生日的时间戳
    //如果生日字段不为空
    if([self.birthdayLabel.text length] > 0) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy/MM/dd"];//设置目标时间字符串的格式
        NSDate* date = [formatter dateFromString:self.birthdayLabel.text];//将源时间字符串转化为NSDate
        self.datePicker.date = date;
    }
    NSTimeInterval interval = [self.datePicker.date timeIntervalSince1970];
    
    [userInfo setValue:self.birthdayLabel.text forKey:@"birthday"];

    [userInfo setValue:self.introductionTextView.text forKey:@"describe"];
    
    [userInfo setValue:self.schoolLbl.text forKey:@"school"];
    

    [userInfo setValue:self.majorLbl.text forKey:@"major"];

    
    [userInfo writeToFile:userInfoPath atomically:YES];
    
    NSString *userID = userInfo[@"id"];
    NSString *gender = [NSString stringWithFormat:@"%li", (long)sex];
    //上传极光推送的别名和tag
    [JPUSHService setTags:[NSSet setWithObject:gender] aliasInbackground:userID ];
    
    [JPUSHService setTags:[NSSet setWithObject:gender] alias:userID fetchCompletionHandle:^(int iResCode, NSSet *iTags, NSString *iAlias) {
        NSLog(@"极光推送回调 rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, iTags, iAlias);
    }];
    
    //获取头像和其他图片的id
    NSMutableDictionary *headDict = [NSMutableDictionary dictionary];
    NSMutableArray *otherDictArray = [NSMutableArray array];
    NSLog(@"%@", otherDictArray);
    for (NSDictionary *dict in imgIDs) {
        //头像
        if ([dict[@"imgType"] isEqualToString:@"1"]) {
            [headDict setValue:dict[@"id"] forKey:@"id"];
        }
        //其他图片
        else {
            NSDictionary *tempDict = @{@"id" : dict[@"id"]};
            [otherDictArray addObject:tempDict];
        }
    }
    

    NSString *schoolID = [[NSUserDefaults standardUserDefaults]objectForKey:@"schoolID"];

    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{
                                                                                @"token" : [userInfo valueForKey:@"token"],
                                                                                @"nickname" : self.nameTextField.text,
                                                                                @"sex" : sex,
                                                                                @"birthday" : [NSString stringWithFormat:@"%f", interval],
                                                                                @"headerImg" : headDict,
                                                                                @"otherImg" : otherDictArray,
                                                                                @"schoolID" : schoolID
                                                                                }];
    if ([self.introductionTextView.text length] > 0) {
        [dict setObject:self.introductionTextView.text forKey:@"describe"];
    }
    if (![self.majorLbl.text isEqualToString:@"没有填写"]) {
        NSString *majorID = [[NSUserDefaults standardUserDefaults]objectForKey:@"majorID"];
        [dict setObject:majorID forKey:@"major"];
    }
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];

    mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html", nil];
    mgr.requestSerializer = [AFJSONRequestSerializer serializer];

    
    
    [mgr POST:[NSString stringWithFormat:@"%@User/saveAll", URL] parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"资料全部保存 %@", responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

@end
